#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<algorithm>
using namespace std;


// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};

//使用Map,不使用map也可以
class Solution {
public:
    Node* copyRandomList(Node* head) {
        map<Node*,Node*> M;
        Node* curr = head;
        while(curr!=NULL){
            Node* copyCurr = new Node(curr->val);
            M.insert(make_pair(curr,copyCurr));
            curr = curr->next;
        }
        curr = head;
        while(curr!=NULL){
            if(curr->next!=NULL){
                M[curr]->next = M[curr->next];
            }
            else{
                M[curr]->next = NULL;
            }
            if(curr->random!=NULL){
                M[curr]->random = M[curr->random];  
            }
            else{
                M[curr]->random = NULL;
            }
            curr = curr->next;
        }
        return M[head];
    }
};

